package com.nowcoder.community.controller;

import com.nowcoder.community.contant.Entity;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/search")
public class SearchController {
    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @GetMapping
    public String search(String keyword, Page page, Model model){
        page.setLimit(5);
        page.setPath("/search?keyword=" + keyword);

        AggregatedPage<DiscussPost> posts = elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());
        List<Map<String, Object>> list = new ArrayList<>();
        for (DiscussPost post: posts){
            Map<String, Object> map = new HashMap<>();
            map.put("post", post);
            map.put("user", userService.findUserById(post.getUserId()));
            map.put("likeCount", likeService.countEntityLikes(Entity.DISCUSS_POST, post.getId()));
            list.add(map);
        }
        page.setRows((int) posts.getTotalElements());
        model.addAttribute("posts", list);
        model.addAttribute("keyword",keyword);
        return "/site/search";
    }
}
